import React from 'react';
import { Modal, Button, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import EditForm from '../EditForm';
import {add} from '@/services/School';

class AddModal extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isShowModal: false,
      isLoading: false
    };
    this.contentRef = React.createRef()
  }

  onShowModal = () => {
    this.setState({ isShowModal: true })
  }

  onCancel = () => {
    this.setState({ isShowModal: false })
  }

  /* 提交数据 */
  onConfirm = async () => {
    try {
      const addSuccessCallback = this.props.add;
      const {validateFields} = this.contentRef.current;
      const values = await validateFields();
      // console.log(values);
      const region = values.region;
      const params = {...values}
      params.province = region[0];
      params.city = region[1];
      params.country = region[2];
      delete params.region;
      this.setState({isLoading: true})
      await add(params);
      addSuccessCallback ? addSuccessCallback() : null;
      message.success('添加成功！');
      this.setState({ isShowModal: false });
    } catch (e) {
      console.error('新增学校：', e);
    } finally {
      this.setState({isLoading: false})
    }
  }

  render() {
    const {isShowModal, isLoading} = this.state;
    const children = this.props.children;
    const contentRef = this.contentRef;
    return (
      <div>
        <Button loading={isLoading} type="primary" onClick={this.onShowModal} icon={<PlusOutlined />}>{children}</Button>
        <Modal
          title="新增学校"
          okText="新增"
          width="50vw"
          visible={isShowModal}
          onCancel={this.onCancel}
          onOk={this.onConfirm}>
          <EditForm ref={contentRef} />
        </Modal>
      </div>
    );
  }
};

export default AddModal
